package route

import (
	"bg/libs"
	"encoding/json"
	// "fmt"
	"github.com/garyburd/redigo/redis"
	"net/http"
	"strings"
)

//默认中间件
func Middle(w http.ResponseWriter, r *http.Request, handle func(http.ResponseWriter, *http.Request)) {
	handle(w, r)
}

//登陆中间件
func LoginMiddle(w http.ResponseWriter, r *http.Request, handle func(http.ResponseWriter, *http.Request)) {
	defer func() {
		if err := recover(); err != nil {
			bytes, _ := json.Marshal(map[string]interface{}{
				"code": 400,
				"msg":  err,
			})
			w.Write(bytes)
		}
	}()
	header := r.Header["Content-Type"][0] //header信息,判断请求type
	bytes := []rune(header)
	strindex := strings.Index(header, ";")
	header = string(bytes[:strindex])
	token := ""
	if header == "application/x-www-form-urlencoded" {
		// r.ParseForm()
	} else if header == "multipart/form-data" {
		// r.ParseMultipartForm(2048)
		// fmt.Println(r.MultipartForm.Value)
	}
	// fmt.Printf("\n%+v,%+v\n", r.FormValue, r.PostFormValue)
	token = r.FormValue("token")
	if token == "" {
		token = r.PostFormValue("token")
	}
	if token == "" {
		panic("请登录...")
	}
	conn, err := libs.RedisCon()
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	str, err := redis.String(conn.Do("get", token))
	if err != nil {
		panic("请登录...")
	}
	jsonBytes := []byte(str)
	mapData := make(map[string]interface{})
	if err := json.Unmarshal(jsonBytes, &mapData); err != nil {
		panic(err)
	}
	if len(mapData) <= 0 {
		panic("请登录...")
	}
	handle(w, r)
}
